package osami.communication;

import java.io.IOException;
import java.net.Socket;

//import osami.communication.engine.OsamiEngine;

/**
 * Connection factory creates connection objects.
 * 
 * @author osami
 *
 */
public class ConnectionFactory
{
	private Activator iEngine = null;
	private CommServer iCommServer = null;
	
	/**
	 * Creates a new instance of ConnectionFactory.
	 * 
	 * @param aEngine OsamiEngine
	 * @param aCommServer CommServer
	 */
	public ConnectionFactory( Activator aEngine, CommServer aCommServer )
	{
		iEngine = aEngine;
		iCommServer = aCommServer;
	}
	
	/**
	 * Connects to given address and returns the created connection object.
	 * The type of the connection to be created is defined by the type of the
	 * address object.
	 * 
	 * @param aAddress
	 * @return Connection
	 * @throws IOException
	 */
	public Connection connectTo( Address aAddress ) throws IOException
	{
		Connection connection = null;
		
		if ( aAddress.getClass() == TCPIPAddress.class )
		{
			System.out.println( "ConnectionFactory.connectTo: Connecting to " + aAddress.toString() + "..." );
			connection = new TCPIPConnection( iEngine, iCommServer, new Socket( aAddress.toString(), TCPIPConnectionListener.PORT ) );
		}
		else if ( aAddress.getClass() == BluetoothAddress.class )
		{
			System.out.println( "ConnectionFactory.connectTo: Connecting to " + aAddress.toString() + "..." );
			connection = new BluetoothConnection( iEngine, iCommServer, aAddress );
		}
		else if ( aAddress.getClass() == BluetoothLongAddress.class )
		{
			System.out.println( "ConnectionFactory.connectTo: Connecting to " + aAddress.toString().substring( 8, 20 ) + "..." );
			connection = new BluetoothConnection( iEngine, iCommServer, aAddress );
		}
		else
		{
			// throw exception
			throw new IOException( "Unknown address type: " + aAddress.getClass().toString() );
		}
		
		return connection;
	}
}
